package main

import (
	"encoding/xml"
	"io/ioutil"

	"jgt-wallet/src/gopay/alipay"
	"jgt-wallet/src/gopay/unionpay"
	"jgt-wallet/src/gopay/wechat"
	"jgt-wallet/src/logger"

	"github.com/spf13/viper"
)

func initClient() {
	initAlipayApp()
	initWechatApp()
	initUnionpayB2b()
}

// 初始化AliPay
func initAlipayApp() {
	alipayAppMap := viper.GetStringMapString("alipay_app")
	for k, v := range alipayAppMap {
		var conf alipay.XmlConfig
		data, err := ioutil.ReadFile(v)
		if err != nil {
			logger.System(traceID).Errorf("支付宝APP启动失败[%s][%s]", k, err.Error())
			continue
		}
		err = xml.Unmarshal(data, &conf)
		if err != nil {
			logger.System(traceID).Errorf("支付宝APP启动失败[%s][%s]", k, err.Error())
			continue
		}
		err = alipay.SetAppClient(k, &(conf.AppConfig))
		if err != nil {
			logger.System(traceID).Errorf("支付宝APP启动失败[%s][%s]", k, err.Error())
			continue
		}
		logger.System(traceID).Infof("启动支付宝APP[%s][%s]", k, conf.AppID)
	}
	return
}

// 初始化Wechat
func initWechatApp() {
	wechatAppMap := viper.GetStringMapString("wechat_app")
	for k, v := range wechatAppMap {

		var conf wechat.XmlConfig
		data, err := ioutil.ReadFile(v)
		if err != nil {
			logger.System(traceID).Errorf("微信APP启动失败[%s][%s]", k, err.Error())
			continue
		}
		err = xml.Unmarshal(data, &conf)
		if err != nil {
			logger.System(traceID).Errorf("微信APP启动失败[%s][%s]", k, err.Error())
			continue
		}
		err = wechat.SetAppClient(k, &(conf.AppConfig))
		if err != nil {
			logger.System(traceID).Errorf("微信APP启动失败[%s][%s]", k, err.Error())
			continue
		}
		logger.System(traceID).Infof("启动微信APP[%s][%s]", k, conf.AppID)
	}
	return
}

func initUnionpayB2b() {
	unionpayB2bMap := viper.GetStringMapString("unionpay_b2b")
	for k, v := range unionpayB2bMap {
		var conf unionpay.XmlConfig
		data, err := ioutil.ReadFile(v)
		if err != nil {
			logger.System(traceID).Errorf("银联B2B启动失败[%s][%s]", k, err.Error())
			continue
		}
		err = xml.Unmarshal(data, &conf)
		if err != nil {
			logger.System(traceID).Errorf("银联B2B启动失败[%s][%s]", k, err.Error())
			continue
		}
		err = unionpay.SetB2bClient(k, &(conf.B2bConfig))
		if err != nil {
			logger.System(traceID).Errorf("银联B2B启动失败[%s][%s]", k, err.Error())
			continue
		}
		logger.System(traceID).Infof("启动银联B2B[%s][%s]", k, conf.SellerID)
	}
	return
}
